//
//  ByUIProductDetailVC.m
//  oc_knowledge
//
//  Created by pro on 17/1/11.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByUIProductDetailVC.h"

// vc
#import "ByUIProductEvaluateVC.h"               // 商品评价
#import "ByUIProductDetailSkuSelectVC.h"        // 规格选择
#import "ByUIProductActivityVC.h"               // 商品详情的活动介绍视图
#import "ByUIShopCarVC.h"                       // 购物车

// view
#import "ByViewDetailHeaderCarousel.h"          // 轮播视图
#import "ByViewDetailToolBar.h"                 // 工具视图
#import "ByViewDetailSegment.h"                 // 分类选择视图
#import "ByViewDetailParams.h"                  // 产品参数视图
#import "ZKPopWindowMenuView.h"                 // 更多弹框
#import "ByViewDetailShare.h"                   // 分享

// cell
#import "ByCellProductDetailInfo.h"             // 信息cell
#import "ByCellProductDetailFuncExtension.h"    // 功能拓展cell
#import "ByCellProductDeatilEvaluate.h"         // 评价cell

// api
#import "ByApiProductDetail.h"                  // 商品详情


#import "SkuModel.h"
#import "SkuIdModel.h"
#import "SkuNameModel.h"

@interface ByUIProductDetailVC () <UITableViewDelegate, UITableViewDataSource>

// view
@property (nonatomic, strong) ByViewDetailHeaderCarousel    *carousel;      // 轮播

@property (nonatomic, strong) ByViewDetailShare             *shareView;     // 分享

@property (nonatomic, strong) ByViewDetailToolBar           *toolBar;       // 工具栏

@property (nonatomic, strong) UIScrollView                  *scroll;        // 底部滑动视图
@property (nonatomic, strong) UITableView                   *table;         // 上面的table
@property (nonatomic, strong) ByViewDetailSegment           *segment;       // 选择视图
@property (nonatomic, strong) UIWebView                     *detailWeb;     // 底部网页
@property (nonatomic, strong) ByViewDetailParams            *detailParams;  // 产品参数

// model
@property (nonatomic, strong) ByModelProductDetail          *model;

@end

@implementation ByUIProductDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"商品详情";
    
    [self addLeftBackBarButtonItem];
    [self addBYItemviews:@[@"product_detail_navi_more", @"product_detail_navi_shopCar"] mode:ByNavigationItemModeImage position:ByNavigationItemPositionModeRight];

    
    [self getDetail];
}

#pragma mark - 请求数据
- (void)loading {
    [ByCoreToolAlert showLoadind:@"加载中"];
}
- (void)getDetail {
    ByNetParamsModel *params = [[ByNetParamsModel alloc] init];
    if (self.pid) {
        params.id = self.pid;
    } else {
        params.id = @"4";
    }
    [self performSelector:@selector(loading) withObject:nil afterDelay:0.01];
    [ByApiProductDetail getProductDetail:params success:^(ByNetBaseResult *result) {
        
        [ByCoreToolAlert hideHud];
        
        _model = result.data;
        
        SkuNameModel *nameModel1 = [[SkuNameModel alloc] init];
        nameModel1.sid_des = @"尺寸";
        nameModel1.vidAry_des = @[@"大", @"很小"];
        SkuNameModel *nameModel2 = [[SkuNameModel alloc] init];
        nameModel2.sid_des = @"颜色";
        nameModel2.vidAry_des = @[@"非常黑", @"白"];
        
        SkuIdModel *idModel1 = [[SkuIdModel alloc] init];
        idModel1.sid = @"10";
        idModel1.vidAry = @[@"11", @"12"];
        SkuIdModel *idModel2 = [[SkuIdModel alloc] init];
        idModel2.sid = @"20";
        idModel2.vidAry = @[@"21", @"22"];
        
        SkuModel *model1 = [[SkuModel alloc] init];
        model1.sku_desc = @"大;非常黑";
        model1.sku_id = @"10:11;20:21";
        model1.quantity = @"12";
        model1.price = @"1111";
        SkuModel *model2 = [[SkuModel alloc] init];
        model2.sku_desc = @"很小;非常黑";
        model2.sku_id = @"10:12;20:21";
        model2.quantity = @"11";
        model2.price = @"2222";
        SkuModel *model3 = [[SkuModel alloc] init];
        model3.sku_desc = @"大;白";
        model3.sku_id = @"10:11;20:22";
        model3.quantity = @"12";
        model3.price = @"3333";
        
//        _model.skuAry = @[model1, model2, model3];
//        _model.skuIdAry = @[idModel1, idModel2];
//        _model.skuNameAry = @[nameModel1, nameModel2];
        
        _model.evaluate_sku = @"尺码：大码；颜色分类：七色花";
        _model.evaluate_content = @"东西非常的好，非常的好看，我很满意，谢谢卖家，强烈推荐";
        _model.evaluate_icon = @"";
        _model.evaluate_name = @"任性不认命";
        _model.evaluate_tags = @[@"质量不错",
                                 @"舒适",
                                 @"好看",
                                 @"胖胖",
                                 @"飞飞",
                                 @"NONONO",
                                 @"服务好"];
        
        // 请求到数据后，在创建视图
        [self createToolBar:NO];
        [self createScroll];
        
        self.carousel.imageURLStringDatas = _model.imgs;
        self.detailWeb.hidden = NO;

    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
}

#pragma mark - 创建视图
// 创建工具栏
// hasSegmentation：是否需要分割线
- (void)createToolBar:(BOOL)hasSegmentation {
    
    // 工具栏主视图
    CGRect frame = CGRectMake(0, 0, SCREEN_WIDTH, 40);
    NSArray *mainTitles = @[@"加入购物车", @"立即购买"];
    NSArray *mainFgColors = @[[UIColor whiteColor], [UIColor whiteColor]];
    NSArray *mainBgColors = @[rgba(251, 128, 10, 1), rgba(250, 56, 9, 1)];
    CGFloat mainRatio = 0.5;
    NSArray *subTitles = @[@"客服", @"店铺", @"收藏"];
    NSArray *subImages = @[@"product_detail_tool_servicer", @"product_detail_tool_shop", @"product_detail_tool_uncollect"];
    self.toolBar = [[ByViewDetailToolBar alloc] initWithFrame:frame
                                                   mainTitles:mainTitles
                                                 mainFgColors:mainFgColors
                                                 mainBgColors:mainBgColors
                                                    mainRatio:mainRatio
                                                    subTitles:subTitles
                                                    subImages:subImages];
    __weak typeof(self) weakself = self;
    [self.toolBar setFunctionClickBlock:^(NSInteger index, BOOL selected) {
        if (index == 2) {
            [weakself.toolBar subFunctionStatusModifyWithIndex:2
                                                 currentStatus:selected
                                                  currentTitle:selected ? @"已收藏" : @"收藏"
                                                 currtentImage:selected ? @"product_detail_tool_collect" : @"product_detail_tool_uncollect"];

        }
        if (index == 3) {
            [weakself addToShopcar];
        }
        if (index == 4) {
            [weakself buyNow];
        }
    }];
    self.toolBar.bottom = SCREEN_HEIGHT - 64;
    [self.view addSubview:self.toolBar];
}
// 创建表视图
- (void)createScroll {
    
    // 最底部的scroll，用来做滑动效果
    _scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - self.toolBar.height)];
    _scroll.contentSize = CGSizeMake(SCREEN_WIDTH, _scroll.height * 2);
    _scroll.scrollEnabled = NO;
    [self.view addSubview:_scroll];
    
    // 上部的详情部分
    _table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, _scroll.width, _scroll.height) style:UITableViewStylePlain];
    _table.delegate = self;
    _table.dataSource = self;
    [_scroll addSubview:_table];
    _table.tableHeaderView = self.carousel;
    _table.tableFooterView = [UIView new];
    _table.separatorStyle = UITableViewCellSeparatorStyleNone;

    // 中间的选择视图
    _segment = [[ByViewDetailSegment alloc] initWithFrame:CGRectMake(0, _scroll.height, _scroll.width, 40) segments:@[@"图文详情", @"产品参数"]];
    [_scroll addSubview:_segment];
    __weak typeof(self) weakself = self;
    [_segment setTapAction:^(NSInteger index, NSString *text) {
        [UIView animateWithDuration:0.25 animations:^{
            if (index == 0) {
                weakself.detailWeb.hidden = NO;
                weakself.detailParams.hidden = YES;
            }
            if (index == 1) {
                weakself.detailWeb.hidden = YES;
                weakself.detailParams.hidden = NO;
            }
        }];
        
    }];
    
}


#pragma mark - 懒加载
- (ByViewDetailHeaderCarousel *)carousel {
    
    if (!_carousel) {
        _carousel = [[ByViewDetailHeaderCarousel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH) timerDuration:5];
    }
    return _carousel;
}
- (ByViewDetailShare *)shareView {
    
    if (!_shareView) {
        _shareView = [[ByViewDetailShare alloc] initWithTitles:@[@"QQ", @"微信好友", @"微信朋友圈"] images:nil numOfLines:3];
    }
    return _shareView;
}
- (UIWebView *)detailWeb {
    
    if (!_detailWeb) {
        _detailWeb = [[UIWebView alloc] initWithFrame:CGRectMake(0, _segment.bottom, _scroll.width, _scroll.height - _segment.height)];
        _detailWeb.scrollView.delegate = self;
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com/"]];
        [_detailWeb loadRequest:request];
        [_scroll addSubview:_detailWeb];
        _detailWeb.hidden = NO;
    }
    return _detailWeb;
}
- (ByViewDetailParams *)detailParams {
    
    if (!_detailParams) {
        _detailParams = [[ByViewDetailParams alloc] initWithFrame:self.detailWeb.frame];
        [_scroll addSubview:_detailParams];
        _detailParams.hidden = YES;
        __weak typeof(self) weakself = self;
        [_detailParams setScrollViewDidEndDragging:^(UIScrollView *scrollView, BOOL decelerate) {
            [weakself scrollViewDidEndDragging:scrollView willDecelerate:decelerate];
        }];
        _detailParams.params = @[
                                 @{@"title"  : @"生产日期",
                                   @"detail" : @"2000年12月1日 至 20001年12月1日"},
                                 @{@"title"  : @"包装方式",
                                   @"detail" : @"包装"},
                                 @{@"title"  : @"原产地",
                                   @"detail" : @"浙江杭州"},
                                 @{@"title"  : @"售卖方式",
                                   @"detail" : @"单收"},
                                 @{@"title"  : @"质量保障",
                                   @"detail" : @"质量保障质量保障质量保障质量保障质量保障质量保障质量保障"},
                                 @{@"title"  : @"生鲜存储温度",
                                   @"detail" : @"-18℃"},
                                 ];
    }
    return _detailParams;
}

#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 4;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 1) {
        return 1;
    }
    return 1;
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 信息
    if (indexPath.section == 0) {
        
        ByCellProductDetailInfo *cell = [tableView dequeueReusableCellWithIdentifier:@"infoCell"];
        if (cell == nil) {
            cell = [[ByCellProductDetailInfo alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"infoCell"];
            cell.shareBlock = ^ {
                
                [self share];
            };
        }
        
        ByCellLayoutProductDetailInfo *layout = [[ByCellLayoutProductDetailInfo alloc] init];
        layout.model = self.model;
        cell.layout = layout;
        
        return cell;
    }
    
    // 功能拓展
    if (indexPath.section == 1) {
        
        ByCellProductDetailFuncExtension *cell = [tableView dequeueReusableCellWithIdentifier:@"funcExtentsion"];
        if (cell == nil) {
            cell = [[ByCellProductDetailFuncExtension alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"funcExtentsion"];
        }
        
        return cell;
    }
    
    // 选规格
    if (indexPath.section == 2) {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"skuCell"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"skuCell"];
            cell.backgroundColor = [UIColor whiteColor];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.text = @"选择规格分类";
            cell.textLabel.font = FONT(14);

        }
        return cell;
    }
    
    // 商品评价
    if (indexPath.section == 3) {
        
        ByCellProductDeatilEvaluate *cell = [tableView dequeueReusableCellWithIdentifier:@"evaluateCell"];
        if (cell == nil) {
            cell = [[ByCellProductDeatilEvaluate alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"evaluateCell"];
        }
        ByCellLayoutProductDeatilEvaluate *layout = [[ByCellLayoutProductDeatilEvaluate alloc] init];
        layout.model = self.model;
        cell.layout = layout;
        
        cell.lookMoreBlock = ^{
            ByUIProductEvaluateVC *vc = [[ByUIProductEvaluateVC alloc] init];
            [self by_normalPush:vc hasNavi:YES];
        };
        
        return cell;
    }
    
  
    return [UITableViewCell new];
    
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        ByCellLayoutProductDetailInfo *layout = [[ByCellLayoutProductDetailInfo alloc] init];
        layout.model = self.model;
        return layout.cellFrame.size.height;
    }
    if (indexPath.section == 1) {
        return 40;
    }
    if (indexPath.section == 2) {
        
        return 44;
    }
    if (indexPath.section == 3) {
        ByCellLayoutProductDeatilEvaluate *layout = [[ByCellLayoutProductDeatilEvaluate alloc] init];
        layout.model = self.model;
        return layout.cellFrame.size.height;
    }
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section == 2 || section == 3) {
        return 10;
    }
    
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if (indexPath.section == 1) {
        ByUIProductActivityVC *vc = [[ByUIProductActivityVC alloc] init];
        [self xw_presentViewController:vc withAnimator:self.bottomPopAnimator];
    }
    if (indexPath.section == 2) {
        [self selectSku:0];
    }
}

#pragma mark - 滑动视图代理
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    
    CGFloat offset = scrollView.contentOffset.y;

    if (scrollView == _table) {
        CGFloat scrollEnabelDistance = MAX(scrollView.contentSize.height, scrollView.height) - scrollView.height;

        NSLog(@"上层table的可滑动距离和已滑动距离:%lf, %lf", scrollEnabelDistance, offset);
        if (offset >= scrollEnabelDistance + 40) {
            [UIView animateWithDuration:0.3 animations:^{
                _scroll.contentOffset = CGPointMake(0, _scroll.height);
            } completion:nil];
        }
    } else {
        NSLog(@"上层table的可滑动距离和已滑动距离:, %lf", offset);

        if (offset <= -40) {
            [UIView animateWithDuration:0.3 animations:^{
                _scroll.contentOffset = CGPointMake(0, 0);
            } completion:nil];
        }
    }
}


#pragma mark - 点击事件
// 导航栏右侧点击事件
- (void)rightItemsAction:(NSInteger)rightIndex {
    
    // 更多
    if (rightIndex == 0) {
        
        [ZKPopWindowMenuView showInWindowWithPoint:CGPointMake(SCREEN_WIDTH - 25, 50) menuWidth:120 titles:@[@"消息", @"首页", @"帮助", @"我要反馈", @"分享"] imageNames:@[@"product_detail_more_message", @"product_detail_more_index", @"product_detail_more_bangzhu", @"product_detail_more_back", @"product_detail_more_share"] doneBlock:^ (NSInteger index) {
            
            NSLog(@"%li", index);
        } dismissBlock:nil];

    }
    // 购物车
    if (rightIndex == 1) {
        ByUIShopCarVC *vc = [[ByUIShopCarVC alloc] init];
        [self by_normalPush:vc hasNavi:YES];
    }
}
// 分享
- (void)share {
    
//    [ByCoreToolAlert showOnlyText:@"分享"];
    
    [self.shareView show];
}
// 添加到购物车
- (void)addToShopcar {
    
    [self selectSku:1];
}
// 立即购买
- (void)buyNow {
    
    [self selectSku:2];
}
// 选择规格
- (void)selectSku:(int)status {
    
    if (![self loginIfNoUserId]) {
        return;
    }
    
    ByUIProductDetailSkuSelectVC *vc = [[ByUIProductDetailSkuSelectVC alloc] init];
    vc.detailModel = self.model;
    vc.enterStatus = status;
    vc.addAction = ^ (SkuModel *model, NSInteger count, int status) {
        
        // 加入购物车
        if (status == 1) {
            ByNetParamsModel *params = [[ByNetParamsModel alloc] init];
            params.uid = BY_USER.uid;
            params.s_id = BY_USER.s_id;
            params.id = _model.id;
            params.sku_pkid = model.sku_pkid;
            params.count = [NSString stringWithFormat:@"%li", count];
            [ByApiProductDetail addToShopCar:params success:^(ByNetBaseResult *result) {
                [ByCoreToolAlert showOnlyText:@"添加成功"];
            } failure:^(ByNetBaseResult *result) {
                [ByCoreToolAlert showOnlyText:result.msg];
            }];
        }
        // 立即购买
        else {
            [ByCoreToolAlert showOnlyText:@"暂未开通立即购买功能"];
        }
    };
    [self xw_presentViewController:vc withAnimator:self.bottomPopAnimator];
}


#pragma mark - 辅助方法
// 如果用户没登录就去登录
- (BOOL)loginIfNoUserId {
    
    if (!BY_USER) {
        ByUINLoginVC *vc = [[ByUINLoginVC alloc] init];
        ByBaseNaviController *navi = [[ByBaseNaviController alloc] initWithRootViewController:vc];
        [self presentViewController:navi animated:YES completion:nil];
        return NO;
    }
    return YES;
}

@end
